// 档案数据接口
export interface ArchiveData {
  name: string
  namecode: string
  birthDate: string
  gender: string
  phone: string
  relationship?: string
  createTime: string
  updateTime: string
}

// 生成档案文件
export const generateArchiveFile = (data: ArchiveData): File => {
  const archiveContent = {
    ...data,
    version: '1.0',
    type: 'medical_archive',
    description: '患者基本信息档案'
  }

  const jsonString = JSON.stringify(archiveContent, null, 2)
  const blob = new Blob([jsonString], { type: 'application/json' })
  
  // 生成文件名：姓名_身份证号_时间戳.json
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)
  const fileName = `${data.name}_${data.namecode.slice(-4)}_${timestamp}.json`
  
  return new File([blob], fileName, { type: 'application/json' })
}

// 解析档案文件
export const parseArchiveFile = (file: File): Promise<ArchiveData> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    
    reader.onload = (e) => {
      try {
        const content = e.target?.result as string
        const archiveData = JSON.parse(content)
        
        // 验证档案数据格式
        if (!archiveData.name || !archiveData.namecode || !archiveData.birthDate) {
          throw new Error('档案文件格式不正确')
        }
        
        resolve(archiveData as ArchiveData)
      } catch (error) {
        reject(new Error('解析档案文件失败: ' + (error as Error).message))
      }
    }
    
    reader.onerror = () => {
      reject(new Error('读取文件失败'))
    }
    
    reader.readAsText(file)
  })
}

// 验证档案数据
export const validateArchiveData = (data: Partial<ArchiveData>): { valid: boolean; errors: string[] } => {
  const errors: string[] = []
  
  if (!data.name || data.name.trim() === '') {
    errors.push('姓名不能为空')
  }
  
  if (!data.namecode || data.namecode.trim() === '') {
    errors.push('身份证号不能为空')
  } else if (!/^\d{17}[\dXx]$/.test(data.namecode)) {
    errors.push('身份证号格式不正确')
  }
  
  if (!data.birthDate) {
    errors.push('出生日期不能为空')
  }
  
  if (!data.gender || !['男', '女'].includes(data.gender)) {
    errors.push('性别必须选择男或女')
  }
  
  if (!data.phone || data.phone.trim() === '') {
    errors.push('联系方式不能为空')
  } else if (!/^1[3-9]\d{9}$/.test(data.phone)) {
    errors.push('手机号格式不正确')
  }
  
  return {
    valid: errors.length === 0,
    errors
  }
}
